//
//  EMMBaseApi.m
//  EMMApp
//
//  Created by Mac on 16/5/24.
//  Copyright © 2016年 YiXun. All rights reserved.
//

#import "EMMBaseApi.h"
#import "JSONKit.h"

@implementation EMMBaseApi
- (instancetype)init
{
    self = [super init];
    if (self) {
        
    }
    return self;
}

//返回数据请求的方式 
- (YTKRequestMethod)requestMethod
{
    return YTKRequestMethodPost;
}

- (YTKRequestSerializerType)requestSerializerType
{
    return YTKRequestSerializerTypeHTTP;
}

- (void)startWithCompletionBlockWithSuccess:(void (^)(YTKBaseRequest *request))success
                                    failure:(void (^)(YTKBaseRequest *request))failure
{
    NSLog(@"请求开始////////////////////////////////////////////////////////////////////////////////////////////////////");
    
    NSDictionary *resa = [self requestArgument];
    if (resa != nil) {
        NSString *str = [resa objectForKey:@"body"];
        NSLog(@"=====> \n%@%@?body=%@", apiBaseUrl, [self requestUrl], str);
        
    }
    
    [self setCompletionBlockWithSuccess:success failure:failure];
    [self start];
    
}

- (void)setCompletionBlockWithSuccess:(void (^)(YTKBaseRequest *request))success
                              failure:(void (^)(YTKBaseRequest *request))failure
{
    self.successCompletionBlock = success;
    self.failureCompletionBlock = failure;
}

- (BOOL)checkNeedCacheData
{
    if (self.ignoreCache) {
        return NO;
    }
    
    if ([self cacheTimeInSeconds] < 0) {
        return NO;
    }
    
    if ([self isCacheVersionExpired]) {
        return NO;
    }
    
    return YES;
}

- (NSString *)responseString {
    if ([self checkNeedCacheData]) {
        id obj = [self cacheJson];
        if (!obj) {
            return nil;
        } else {
            return [obj JSONString];
        }
    } else {
        return self.requestOperation.responseString;
    }
}

@end
